﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;

namespace MvcSample.Data
{
    public static class ApplicationContextMigrationExt
    {
        public static IWebHost Migrate<TContext>(this IWebHost webHost, Action<TContext> action)
            where TContext : DbContext
        {
            using (var scope = webHost.Services.CreateScope())
            {
                var sp = scope.ServiceProvider;

                var ctx = sp.GetRequiredService<TContext>();
                var logger = sp.GetRequiredService<ILogger<TContext>>();

                try
                {
                    ctx.Database.Migrate();
                    action.Invoke(ctx);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "种子数据迁移失败");
                }
                return webHost;
            }
        }
    }
}
